#!/usr/bin/env python
# -*- coding: utf-8 -*-

__all__ = ['compiler', 'context', 'dom', 'processor', 'tokenizer']
__version__ = '$Id$'

import jsCSS.processor

from jsCSS.dom import Document
from jsCSS.compiler import Compiler

def process(string, processors=None, context=None):
    """Process the given string and return resulting CSS. Processors is an
    optional list of objects that can extend the string."""
    if processors is None:
        def create_processor(name):
            return getattr(jsCSS.processor, name)()
        processors = map(create_processor, jsCSS.processor.__all__)

    context_processor = None
    try:
        if context is not None and hasattr(context, 'processor'):
            context_processor = context.processor
            del context.processor
            processors.append(context_processor)

        # Pre-processing
        last_processor = None
        document = Document().from_string(string)
        for processor in processors:
            if last_processor is not None:
                processor = processor.inherit(last_processor)
            string = processor.pre_process(document, string)
            last_processor = processor

        # Compile and run
        compiler = Compiler()
        result = compiler.compile_and_run_string(string, context)

        # Post-processing
        if result is not None:
            document = Document().from_string(result)
            first_processor, last_processor = None, None
            for processor in processors:
                if first_processor is None:
                    processor.reset()
                if last_processor is not None:
                    processor = processor.inherit(last_processor)
                result = processor.post_process(document, result)
                first_processor, last_processor = processor, processor
    finally:
        if context_processor is not None:
            context.processor = context_processor

    return result
